const express = require('express')
const cors = require('cors')
const fs = require('fs')
const app = express()

// 处理跨域
app.use(cors())

// 中间件：设置响应头部信息
const setHeaderMiddleware = (req, res, next) => {
  res.setHeader('Content-Type', 'application/json'); // 设置响应的Content-Type头部信息为application/json
  next(); // 调用next()继续执行下一个中间件或路由处理程序
}
// 配置解析 application/json 格式数据的内置中间件
app.use(express.json())

// 应用中间件到所有路由
app.use(setHeaderMiddleware);

/*
  usersList  查询所有用户信息
  addUser  添加用户信息 
  delUser 删除用户信息
  editUser 删除用户信息
  :id 查询单个用户信息
*/ 

// 查
app.get('/usersList', function(req, res){
  let searchName = req.query.name
  try {
    const data = fs.readFileSync(`${__dirname}/static/users.json`)
    let userList = JSON.parse(data)
    let resList = searchName ? userList.filter(item => item.name === searchName) : userList
    res.end(JSON.stringify(resList))
  } catch (error) {
    let errInfo = {
      code: -1,
      msg: '读取用户列表失败'
    }
    res.end(JSON.stringify(errInfo))
  }
})

const EditUserInfo = (newList) => {
  fs.writeFile(`${__dirname}/static/users.json`, JSON.stringify(newList, null, 2), function(err) {
    if (err) {
      console.error(err)
      res.status(500).end('Error writing file')
      return
    }
  })
}

// 增
app.post('/addUser', function(req, res){
  let newUserInfo = req.body
  try {
    const data = fs.readFileSync(`${__dirname}/static/users.json`)
    let userList = JSON.parse(data)
    newUserInfo.id = userList[userList.length-1].id + 1
    userList.push(newUserInfo)
    EditUserInfo(userList)
    let resInfo = {
      code: 200,
      msg: '添加用户信息成功！'
    }
    res.end(JSON.stringify(resInfo))
  } catch (error) {
    let errInfo = {
      code: -1,
      msg: '添加用户信息失败'
    }
    res.end(JSON.stringify(errInfo))
  }
})

// 删
app.get('/delUser', function(req, res){
  let delID = req.query.id
  let delInfo = {}
  try {
    const data = fs.readFileSync(`${__dirname}/static/users.json`)
    let userList = JSON.parse(data)
    let findIdIndex = userList.findIndex(item => item.id === +delID)
    if(findIdIndex !== -1){
      userList.splice(findIdIndex, 1)
      EditUserInfo(userList)
      delInfo = {
        code: 200,
        msg: '删除用户信息成功！'
      }
    }else{
      delInfo = {
        code: -1,
        msg: 'findIdIndex删除用户信息失败！'
      }
    }
  } catch (error) {
    console.log('error', error)
    delInfo = {
      code: -1,
      msg: 'catch删除用户信息失败！'
    }
  }finally{
    res.end(JSON.stringify(delInfo))
  }
})


// 批量删
app.delete('/delUsers', function(req, res){
  let delIDs = req.query.ids
  console.log('delIDsdelIDs', delIDs)
  let delInfo = {}
  try {
    const data = fs.readFileSync(`${__dirname}/static/users.json`)
    let userList = JSON.parse(data)
    let newList = userList.filter(item => !delIDs.includes(''+item.id))
    EditUserInfo(newList)
    delInfo = {
      code: 200,
      msg: '批量删除用户信息成功！'
    }
  } catch (error) {
    console.log('error', error)
    delInfo = {
      code: -1,
      msg: 'catch批量删除用户信息失败！'
    }
  }finally{
    res.end(JSON.stringify(delInfo))
  }
})

// 改
app.put('/editUser', function(req, res){
  let newUserInfo = req.body
  let editInfo = {}
  try {
    const data = fs.readFileSync(`${__dirname}/static/users.json`)
    let userList = JSON.parse(data)
    let findIndex = userList.findIndex(item => item.id === newUserInfo.id)
    if(findIndex !== -1){
      userList[findIndex] = newUserInfo
      EditUserInfo(userList)
      editInfo = {
        code: 200,
        msg: '修改用户信息成功！'
      }
    }else{
      editInfo = {
        code: -1,
        msg: '修改用户信息失败！'
      }
    }
  } catch (error) {
    console.log('error', error)
    editInfo = {
      code: -1,
      msg: '修改用户信息失败'
    }
  }finally{
    res.end(JSON.stringify(editInfo))
  }
})


app.listen('9091')